import React from "react";
import PubSub from "pubsub-js";
import Dialog from "../Dialog";
import sizeFormat from "../../utils/sizeFormat";

import otherSVG from "../../assets/file-icon/other.svg"

import "./index.scss"


/*export default function UploadTask(props) {
    
    const [taskList, setTaskList] = useState([])
    const [visible, setVisible] = useState(false)
    
    useEffect(() => {
        function uploadChunk({ taskId, chunkList, index, hash}) {
            let formData = new FormData();
            formData.append('file', chunkList[index].file)
            formData.append('seq', chunkList[index].seq)
            formData.append('taskId', taskId)
            fileNodeApi.uploadChunk(formData).then(({ data: { process, finished } }) => {
                if (finished) {
                    setTaskList(taskList => {
                        for (let i = 0;i < taskList.length;i++) {
                            if (taskList[i].hash === hash) {
                                taskList[i].process = (process * 100).toFixed(2) + "%"
                                break
                            }
                        }
                        return [...taskList]
                    })
                    PubSub.publish('EV_FLASH_FILE_NODE')
                    upload()
                }
                else {
                    setTaskList(taskList => {
                        for (let i = 0;i < taskList.length;i++) {
                            if (taskList[i].hash === hash) {
                                taskList[i].process = (process * 100).toFixed(2) + "%"
                                break
                            }
                        }
                        return [...taskList]
                    })
                    index++
                    uploadChunk({taskId, chunkList, index, hash})
                }
            })
        }

        async function upload() {
            if (waitUploadFiles.length <= 0) return

            let waitUploadFile = waitUploadFiles.pop()

            /!*console.log(waitUploadFile.name)*!/

            waitUploadFile.md5 = await fileTool.md5(waitUploadFile.chunkList)
            setTaskList(taskList => {
                for (let i = 0;i < taskList.length;i++) {
                    if (taskList[i].hash === waitUploadFile.hash) {
                        taskList[i].status = true
                        break
                    }
                }
                return [...taskList]
            })

            let { data: { taskId } } = await fileNodeApi.createUpload({
                name: waitUploadFile.name,
                md5: waitUploadFile.md5,
                size: waitUploadFile.size,
                lastModified: waitUploadFile.lastModified,
                chunkCount: waitUploadFile.chunkList.length,
                parentId: waitUploadFile.parentId
            })
            uploadChunk({ taskId: taskId, chunkList: waitUploadFile.chunkList, index: 0, hash: waitUploadFile.hash})
        }

        PubSub.subscribe('EV_ADD_TASK', (_, { files, root }) => {
            let list = []
            for (let i = 0;i < files.length;i++) {
                let file = files[i]
                let hash = uuid()
                list.push({
                    fileName: file.name,
                    size: file.size,
                    hash: hash,
                    uploadPath: root.name,
                    process: '0%',
                    status: false
                })
                waitUploadFiles.push({
                    hash: hash,
                    name: file.name,
                    size: file.size,
                    lastModified: file.lastModified,
                    chunkList: fileTool.chunk(file),
                    parentId: root.id
                })
                if (taskList < 6) {
                    upload()
                }
            }
            setTaskList([...taskList, ...list])
            if (!visible) setVisible(true)
        })
    }, [taskList, visible])



    function close() {
        setVisible(false)
    }

    return (
        <Dialog visible={ visible } close={ close } >
            <div className={ 'upload-task-header' }>
                <div className={ 'file-name' }>文件（夹）名</div>
                <div className={ 'file-size' }>大小</div>
                <div className={ 'file-path' }>上传目录</div>
                <div className={ 'file-status' } />
                <div className={ 'file-operate' } />
            </div>
            {
                taskList.map((task, index) => {
                    return (
                        <div className={ 'upload-task' } key={ task.hash }>
                            <div className={ 'process' } style={{ width: task.process }} />
                            <div className={ 'file-name' }>
                                <img src={ otherSVG } alt={ '' } />
                                <span>{ task.fileName }</span>
                            </div>
                            <div className={ 'file-size' }> { sizeFormat(task.size) } </div>
                            <p className={ 'file-path' }> { task.uploadPath } </p>
                            <div className={ 'file-status' }>{ task.status ? task.process : '等待上传' }</div>
                            <div className={ 'file-operate' }><span className={ 'icon-cancel' } /> </div>
                        </div>
                    )
                })
            }

        </Dialog>
    )
}*/

export default class UploadTask extends React.Component {

    state = {
        visible: false,
        taskList: []
    }

    close() {
        this.setState({ visible: false })
    }

    update(hash, o) {
        let taskList = this.state.taskList
        for (let i = 0;i < taskList.length;i++) {
            if (taskList[i].hash === hash) {
                taskList[i] = {...taskList[i], ...o}
                this.setState({ taskList: [...taskList] })
                break
            }
        }
    }

    componentDidMount() {
        PubSub.subscribe('EV_TASK_ADD', (_, task) => {
            this.setState({ taskList: [...this.state.taskList, task] })
            if (!this.state.visible) this.setState({ visible: true })
        })
        PubSub.subscribe('EV_TASK_UPDATE', (_, { hash, data }) => {
            this.update(hash, data)
        })
    }

    render() {
        return (
            <Dialog visible={ this.state.visible } close={ e => { this.close(e); } } >
                <div className={ 'upload-task-header' }>
                    <div className={ 'file-name' }>文件（夹）名</div>
                    <div className={ 'file-size' }>大小</div>
                    <div className={ 'file-path' }>上传目录</div>
                    <div className={ 'file-status' } />
                    <div className={ 'file-operate' } />
                </div>
                {
                    this.state.taskList.map((task, index) => {
                        return (
                            <div className={ 'upload-task' } key={ task.hash }>
                                {
                                    task.status !== 'finished'
                                    ? (<div className={ 'process' } style={{ width: task.process }} />)
                                    : (<></>)
                                }
                                <div className={ 'file-name' }>
                                    <img src={ otherSVG } alt={ '' } />
                                    <span>{ task.fileName }</span>
                                </div>
                                <div className={ 'file-size' }> { sizeFormat(task.size) } </div>
                                <div className={ 'file-path' }> { task.uploadPath } </div>
                                <div className={ 'file-status' }>
                                    {
                                        task.status === 'finished'
                                        ? (<span className='icon icon-checked' />)
                                        : (<span>{ task.status === 'uploading' ? task.process : '排队中...' }</span>)
                                    }
                                </div>
                                <div className={ 'file-operate' }>
                                    {
                                        task.status !== 'finished'
                                        ? (<span className={ 'icon-cancel' } />)
                                        : (<></>)
                                    }
                                </div>
                            </div>
                        )
                    })
                }

            </Dialog>
        )
    }
}